public class Solution393 {
    public boolean validUtf8(int[] data) {
        int cur=0;
        while (cur<data.length){
            int m=data[cur];
            if ((m&(1<<7))==0){
                cur++;
            }else{
                int k=0;
                for (int j=7;j>=0;j--){
                    if ((m&(1<<j))==0){
                        break;
                    }else{
                        k++;
                    }
                }
                if (k>4 || k==1){
                    return false;
                }
                for (int j=0;j<k-1;j++){
                    cur++;
                    if (cur>=data.length || data[cur]<128){
                        return false;
                    }
                }
                cur++;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new Solution393().validUtf8(new int[]{235,140,4}));
    }
}
